#include"Stack&Queue.h"


void StackInit(STNode* ps)
{
	assert(ps);
	ps->capacity = 0;
	ps->data = NULL;
	ps->top = 0;
}
void StackDestory(STNode* ps)
{
	assert(ps);
	free(ps->data);
	ps->data = NULL;
	ps->capacity = 0;
	ps->top = 0;
}
void StackPush(STNode* ps,STdatatype x)
{
	assert(ps);
	if (ps->top == ps->capacity)
	{
		int newCapacity = (ps->capacity == 0 ? 4 : 2 * ps->capacity);
		STdatatype* tmp = (STdatatype*)realloc(ps->data, newCapacity*sizeof(STdatatype));
		if (tmp == NULL)
		{
			perror("Stack realloc failed");
			exit(-1);
		}
		ps->capacity = newCapacity;
		ps->data = tmp;
	}
	ps->data[ps->top] = x;
	ps->top++;
}
void StackPop(STNode* ps)
{
	assert(ps);
	assert(ps->top > 0);

	ps->top--;
}
STdatatype StackTop(STNode* ps)
{
	assert(ps);
	assert(ps->top > 0);

	return ps->data[ps->top-1];
}
int StackSize(STNode* ps)
{
	assert(ps);

	return ps->top;
}
bool StackEmpty(STNode* ps)
{
	assert(ps);

	return ps->top == 0;
}



void QueueInit(QU* pq)
{
	assert(pq);
	pq->head = NULL;
	pq->tail = NULL;
	pq->size = 0;
}
void QueueDestory(QU* pq)
{
	assert(pq);
	QUNode* cur = pq->head;
	while (cur!=NULL)
	{
		QUNode* next = cur->next;
		free(cur);
		cur = next;
	}
}
void QueuePush(QU* pq,QUdatatype x)
{
	assert(pq);
	QUNode* newnode = (QUNode*)malloc(sizeof(QUNode));
	if (newnode == NULL)
	{
		perror("Queue malloc failed");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	if (pq->head == NULL)
	{
		pq->head = newnode;
		pq->tail = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}
	pq->size++;
}

void QueuePop(QU* pq)
{
	assert(pq);
	assert(pq->head != NULL);
	if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = NULL;
		pq->tail = NULL; 
	}
	else
	{
		QUNode* next = pq->head->next;
		free(pq->head);
		pq->head = next;
	}
	pq->size--;
}
QUdatatype QueueFront(QU* pq)
{
	assert(pq);
	assert(pq->head);
	if (!QueueEmpty(pq));
	return pq->head->data;
}
QUdatatype QueueBack(QU* pq)
{
	assert(pq);
	assert(pq->head);
	if (!QueueEmpty(pq));
	return pq->tail->data;
}
int QueueSize(QU* pq)
{
	assert(pq);
	assert(pq->head);
	if (!QueueEmpty(pq));
	return pq->size;
}
bool QueueEmpty(QU* pq)
{
	assert(pq);

	return pq->head == NULL;
}

